import { isArray } from '@kukefe/kkutils'

import { isUndefined } from './index'

import { AesEncryption } from './cipher'

// 创建AES加密对象
const aes = new AesEncryption()
/**
 *
 * @description 解密:反序列化字符串参数
 */
export const parseQuery = (query: string): any => {
  query = decodeURIComponent(query)
  const res: any = {}

  query = query.trim().replace(/^(\?|#|&)/, '')

  if (!query) return res

  query = aes.decryptByAES(query)

  query.split('&').forEach((param) => {
    const parts = param.replace(/\+/g, ' ').split('=')
    const key = parts.shift()
    const val = parts.length > 0 ? parts.join('=') : null

    if (!isUndefined(key)) {
      if (isUndefined(res[key])) {
        res[key] = val
      } else if (isArray(res[key])) {
        ;(res[key] as any[]).push(val)
      } else {
        res[key] = [res[key] as any, val]
      }
    }
  })

  return res
}
